/*
 *这个类提供了把汉字转换成拼音，保存到数据库或者文件中。
 */
package com.res0w.SMMS.factory;

import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 *
 * @author res0w
 * @since 2009-9-13
 * @version 0.1
 * @param hanzi 输入汉字
 * 
 */
public class ChineseChar2Pinyin {

    public static String hanzi2Pinyin(String hanzi) {
        /*
         * 设置拼音格式
         */
        HanyuPinyinOutputFormat pinyinFormat = new HanyuPinyinOutputFormat();
        pinyinFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);//输出拼音一律大写
        pinyinFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//没有音调
        pinyinFormat.setVCharType(HanyuPinyinVCharType.WITH_V);//字符设置

        CharSequence hanziProfile = hanzi;
        int charLength = hanziProfile.length();
        char[] singalHanzi = new char[hanziProfile.length()];
        String[] pinyin = new String[hanziProfile.length()];

        String py = "";
        for (int i = 0; i < charLength; i++) {
            try {
                singalHanzi[i] = hanziProfile.charAt(i);
                pinyin = PinyinHelper.toHanyuPinyinStringArray(singalHanzi[i], pinyinFormat);
                py = py + pinyin[0];
            } catch (BadHanyuPinyinOutputFormatCombination ex) {
                Logger.getLogger(ChineseChar2Pinyin.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return py.trim();
    }
    /*
     * 测试部分
     *

    public static void main(String[] args) {
        String testHanzi = "我吕正恶这个扫激发空担负阿凡达";
        System.out.println(testHanzi);
        System.out.println(hanzi2Pinyin(testHanzi));
    }
     */
}


